package com.gylang.print.pdf.render;

import com.gylang.print.pdf.domain.PdfPageWrapper;
import com.gylang.print.pdf.domain.PdfWrapper;
import com.gylang.print.pdf.domain.component.img.ImgComponent;
import com.gylang.print.pdf.enums.PdfComponentEnums;
import com.gylang.print.pdf.util.PdfUtil;

import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author gylang
 * data 2021/6/6
 */
public class ImgPdfRender implements IPdfRender<ImgComponent> {
	@Override
	public String type() {
		return PdfComponentEnums.IMG.getType();
	}

	@Override
	public void render(PdfWrapper wrapper, PdfPageWrapper pageWrapper, ImgComponent component) {

		// 图片写入
		// 获取 图片
		try {

			// 缩放
			BufferedImage image = PdfUtil.getImg(component);
			float width = component.getWidth();
			float height = component.getHeight();
			float sx = width / image.getWidth();
			float sy = height / image.getHeight();
			Graphics2D imageGraphics = image.createGraphics();
			AffineTransform transform = imageGraphics.getTransform();
			transform.scale(sx, sy);
			imageGraphics.setTransform(transform);
			imageGraphics.dispose();

			// 获取位置
			float x = PdfUtil.getX(pageWrapper.getWidth(), pageWrapper.getMarginLeftX(), pageWrapper.getMarginRightX(),
				component.getX(), width, component.getAlign());
			float y = PdfUtil.getY(pageWrapper.getHeight(), pageWrapper.getMarginTopY(), pageWrapper.getMarginBottomY(),
				component.getY(), height, component.getAlign());

			// 渲染
			PdfUtil.writeImg(pageWrapper.getContentStream(), PdfUtil.getPDImageXObject(wrapper.getDocument(), image, component.getSuffix()),
				x, y, width, height);

		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
